<?php
/***
* @version $Id: functions.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2006              kkroo < princeomz2004@hotmail.com > (Omar Ramadan) http://phpbb-login.sourceforge.net
*            (c) 2006              Afterlife_69 < afterlife_69@hotmail.com > (Dean Newman) http://www.ugboards.com
*            (c) 2005 - 2006 Fountain of Apples < webmacster87@gmail.com > (Douglas Bell) http://www.webmacster87.info
*            (c) 2005 - 2006 aboyd (Tony Boyd) http://www.outshine.com/forums/
*            (c) 2005 - 2006 pichirichi <pichirichi@pichirichi.com> http://www.pichirichi.com
*            (c) 2005 - 2006 Prent < prent@milkohol.net >
*            (c) 2005 - 2006 -SV- < esizemore05@gmail.com > (Eric Sizemore)
*            (c) 2004 - 2006 addit, Chris Russell, Raimon <Raimon@phpBBservice.nl> htp://phpBBservice.nl
*            (c) 2002 - 2006 Karl Tauber < karl@ktauber.com > - www.ktauber.com
*            (c) 2005              chatasos < chatasos@psclub.gr > (Tassos Chatzithomaoglou) http://www.psclub.gr
*            (c) 2005              pentapenguin < pentapenguin @at-no-spam@ bluebottle.com > (Jeremy Conley) http://www.pentapenguin.com
*            (c) 2005              lowjoel <webmaster@joelsplace.sg> Joel Low - http://joelsplace.sg/
*            (c) 2004 - 2005 markus_petrux < phpbb.mods@phpmix.com > (Markus) http://www.phpmix.com
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if ( !defined('IN_R3BORN') )
{
	die('Hacking attempt');
}

function get_db_stat($mode)
{
	global $db;

	switch( $mode )
	{
		case 'usercount':
			$sql = "SELECT COUNT(user_id) AS total
				FROM " . USERS_TABLE . "
				WHERE user_id <> " . ANONYMOUS;
			break;

		case 'newestuser':
			$sql = "SELECT user_id, username
				FROM " . USERS_TABLE . "
				WHERE user_id <> " . ANONYMOUS . "
				AND user_active = 1
				ORDER BY user_id DESC
				LIMIT 1";
			break;
	}

	if ( !($result = $db->sql_query($sql)) )
	{
		return false;
	}

	$row = $db->sql_fetchrow($result);

	switch ( $mode )
	{
		case 'usercount':
			return $row['total'];
			break;
		case 'newestuser':
			return $row;
			break;
	}
	return false;
}

// Properly format the username
function r3born_clean_username($username)
{
	$username = substr(htmlspecialchars(str_replace("\'", "'", trim($username))), 0, 25);
	$username = r3born_rtrim($username, "\\");
	$username = str_replace("'", "\'", $username);

	return $username;
}

/**
* This function is a wrapper for ltrim, as charlist is only supported in php >= 4.1.0
*/
function r3born_ltrim($str, $charlist = false)
{
	if ($charlist === false)
	{
		return ltrim($str);
	}
	else
	{
		return ltrim($str, $charlist);
	}

	//$php_version = explode('.', PHP_VERSION);

	// php version < 4.1.0
	//if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
	//{
	//	while ($str{0} == $charlist)
	//	{
	//		$str = substr($str, 1);
	//	}
	//}
	//else
	//{
	//	$str = ltrim($str, $charlist);
	//}

	//return $str;
}

// fix a bug in PHP 4.3.10 (only supporting charlist in php >= 4.1.0)
function r3born_rtrim($str, $charlist = false)
{
	if ($charlist === false)
	{
		return rtrim($str);
	}
	else
	{
		return rtrim($str, $charlist);
	}
/*
	$php_version = explode('.', PHP_VERSION);

	// php version < 4.1.0
	if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
	{
		while ($str{strlen($str)-1} == $charlist)
		{
			$str = substr($str, 0, strlen($str)-1);
		}
	}
	else
	{
		$str = rtrim($str, $charlist);
	}

	return $str;
*/
}

/**
* Our own generator of random values
* This uses a constantly changing value as the base for generating the values
* The board wide setting is updated once per page if this code is called
* With thanks to Anthrax101 for the inspiration on this one
*
*/
function dss_rand()
{
	global $db, $config, $dss_seeded;

	$val = $config['rand_seed'] . microtime();
	$val = md5($val);
	$config['rand_seed'] = md5($config['rand_seed'] . $val . 'a');

	if($dss_seeded !== true)
	{
		$sql = "UPDATE " . CONFIG_TABLE . " SET
			config_value = '" . $config['rand_seed'] . "'
			WHERE config_name = 'rand_seed'";

		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "Unable to reseed PRNG", "", __LINE__, __FILE__, $sql);
		}

		$dss_seeded = true;
	}

	return substr($val, 4, 16);
}

// -----------------------
// Page specific functions
//
function gen_rand_string($hash)
{
	$rand_str = dss_rand();

	return ( $hash ) ? md5($rand_str) : substr($rand_str, 0, 8);
}
//
// End page specific functions
// ---------------------------

//
// Get Userdata, $user can be username or user_id. If force_str is true, the username will be forced.
//
function get_userdata($user, $force_str = false)
{
	global $db;

	if (!is_numeric($user) || $force_str)
	{
		$user = r3born_clean_username($user);
	}
	else
	{
		$user = intval($user);
	}

	$sql = "SELECT *
		FROM " . USERS_TABLE . "
		WHERE ";
	$sql .= ( ( is_integer($user) ) ? "user_id = $user" : "username = '" .  str_replace("\'", "''", $user) . "'" ) . " AND user_id <> " . ANONYMOUS;
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Tried obtaining data for a non-existent user', '', __LINE__, __FILE__, $sql);
	}

	return ( $row = $db->sql_fetchrow($result) ) ? $row : false;
}

// $lang_file = STRING - The lang file to search for, for example help_me.php
// $modulename = STRING - The name of the module to search in, if no module name is given then core is searched.
//  Returns the best match for the users choosen language preference.
//
function get_default_lang($lang_file, $modulename = '')
{
	global $root_path, $phpEx, $userdata, $lang, $config, $db;

	if ($modulename != '')
	{
		$lang_path = $root_path . 'modules/' . $modulename . '/language/lang_';
	}
	else
	{
		$lang_path = $root_path . '/language/lang_';
	}

	if ($userdata['user_id'] != ANONYMOUS)
	{
		// For logged in users, try their chosen language
		$default_lang = r3born_ltrim(basename(r3born_rtrim($userdata['user_lang'])), "'");
	}
	else
	{
		// For guests, try the board default language
		$default_lang = r3born_ltrim(basename(r3born_rtrim($config['default_lang'])), "'");
	}

	// If the lang file doesn't exist, then lets try an alternative.
	if (!file_exists(@realpath($lang_path . $default_lang . '/' . $lang_file)))
    {
		if ( $userdata['user_id'] != ANONYMOUS )
		{
			// For logged in users, try the board default language next
			$default_lang = r3born_ltrim(basename(r3born_rtrim($config['default_lang'])), "'");
		}
		else
		{
			// OK, we didn't find a localised lang file, lets try for english and hope for the best
			$default_lang = 'english';
		}

		if (!file_exists(@realpath($lang_path . $default_lang . '/' . $lang_file)))
		{
			// If still not found then default to english regardless of user type. This is a gamble.
			$default_lang = 'english';
		}
    }

	// If we are looking the main lang file in the core and we've had to change the value and in any way then let's write it back to the database
	// before we go any further since it means there is something wrong with it
	if ( $lang_file == 'lang_main.'.$phpEx && $modulename == '' )
	{
		if ( $userdata['user_id'] != ANONYMOUS && $userdata['user_lang'] !== $default_lang )
		{
			$sql = 'UPDATE ' . USERS_TABLE . "
				SET user_lang = '" . $default_lang . "'
				WHERE user_lang = '" . $userdata['user_lang'] . "'";

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(CRITICAL_ERROR, 'Could not update user language info');
			}

			$config['default_lang'] = $default_lang;
			$userdata['user_lang'] = $default_lang;
		}
		elseif ( $userdata['user_id'] == ANONYMOUS && $config['default_lang'] !== $default_lang )
		{
			$sql = 'UPDATE ' . CONFIG_TABLE . "
				SET config_value = '" . $default_lang . "'
				WHERE config_name = 'default_lang'";

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(CRITICAL_ERROR, 'Could not update user language info');
			}

			$config['default_lang'] = $default_lang;
		}
	}

	return $default_lang;
}

//
// Initialise user settings on page load
function init_userprefs($userdata)
{
	global $config, $theme, $images;
	global $template, $lang, $phpEx, $root_path, $db;

### R3-born - ADD (Module Engine)
#
	global $mvModules, $mvModuleName, $mvModule_root_path;
#
### R3-born - END

	if ( $userdata['user_id'] != ANONYMOUS )
	{
		if ( !empty($userdata['user_dateformat']) )
		{
			$config['default_dateformat'] = $userdata['user_dateformat'];
		}

		if ( isset($userdata['user_timezone']) )
		{
			$config['board_timezone'] = $userdata['user_timezone'];
		}
	}

	$default_lang = get_default_lang('lang_main.'.$phpEx);

	if ( !file_exists(@realpath($root_path . 'language/lang_' . $default_lang . '/lang_main.'.$phpEx)) )
	{
		message_die(CRITICAL_ERROR, 'Could not locate valid language pack');
	}

	include($root_path . 'language/lang_' . $default_lang . '/lang_main.' . $phpEx);

	if ( defined('IN_ADMIN') )
	{
		if( !file_exists(@realpath($root_path . 'language/lang_' . $default_lang . '/lang_admin.'.$phpEx)) )
		{
			$default_lang = $config['default_lang'] = 'english';
		}

		include($root_path . 'language/lang_' . $default_lang . '/lang_admin.' . $phpEx);
	}

### R3-born - ADD (Module Engine)
#
    // include the lang files lang_main.php (or lang_admin.php if in the ACP) for all enabled modules
    foreach ($mvModules as $name => $value)
    {
		if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
		{
			//include the language files for each module/block
			foreach ($value['language'] as $n => $file)
       		{
           		if ( $file == 'lang_main.' . $phpEx || ($file == 'lang_admin.' . $phpEx && defined('IN_ADMIN')) )
           		{
					// Try and include the lang file silently, if it doesn't exist then we do not error because it is perfectly OK for a module not to have any lang files at all.
					@include($root_path . 'modules/' . $name . '/language/lang_' . get_default_lang($file, $name) . '/' . $file);
           		}
       		}
		}
    }
#
### R3-born - END

	//
	// Set up style
	//
	if ( !$config['override_user_style'] )
	{

### R3-born - ADD (Change Style)
#
		if ( isset($_GET[STYLE_URL]) )
		{
			$style = urldecode( $_GET[STYLE_URL] );
			if ( $theme = setup_style($style) )
			{
				if ( $userdata['user_id'] != ANONYMOUS )
				{
					// user logged in --> save new style ID in user profile
					$sql = "UPDATE " . USERS_TABLE . "
						SET user_style = " . $theme['themes_id'] . "
						WHERE user_id = " . $userdata['user_id'];
					if ( !$db->sql_query($sql) )
					{
						message_die(CRITICAL_ERROR, 'Error updating user style', '', __LINE__, __FILE__, $sql);
					}

					$userdata['user_style'] = $theme['themes_id'];
				}
				else
				{
					// user not logged in --> save new style ID in cookie
					setcookie($config['cookie_name'] . '_style', $style, time() + 31536000, $config['cookie_path'], $config['cookie_domain'], $config['cookie_secure']);
				}
				return;
			}
		}

		if ( $userdata['user_id'] == ANONYMOUS && isset($_COOKIE[$config['cookie_name'] . '_style']) )
		{
			$style = $_COOKIE[$config['cookie_name'] . '_style'];
			if ( $theme = setup_style($style) )
			{
				return;
			}
		}
#
### R3-born - END ADD

		if ( $userdata['user_id'] != ANONYMOUS && $userdata['user_style'] > 0 )
		{
			if ( $theme = setup_style($userdata['user_style']) )
			{
				return;
			}
		}
	}

	$theme = setup_style($config['default_style']);

	return;
}

function setup_style($style)
{
	global $db, $config, $template, $images, $root_path, $mvModules, $mvModule_root_path, $mvCSS;

	if ( !is_numeric($style) )
	{
		$sql = "SELECT *
			FROM " . THEMES_TABLE . "
			WHERE style_name = '$style'";
	}
	else
	{
		$sql = 'SELECT *
			FROM ' . THEMES_TABLE . '
			WHERE themes_id = ' . (int) $style;
	}

	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not query database for theme info');
	}

	if ( !($row = $db->sql_fetchrow($result)) )
	{
		// We are trying to setup a style which does not exist in the database
		// Try to fallback to the board default (if the user had a custom style)
		// and then any users using this style to the default if it succeeds
		if ( $style != $config['default_style'])
		{
			$sql = 'SELECT *
				FROM ' . THEMES_TABLE . '
				WHERE themes_id = ' . (int) $config['default_style'];

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(CRITICAL_ERROR, 'Could not query database for theme info');
			}

			if ( $row = $db->sql_fetchrow($result) )
			{
				$db->sql_freeresult($result);

				$sql = 'UPDATE ' . USERS_TABLE . '
					SET user_style = ' . (int) $config['default_style'] . "
					WHERE user_style = $style";

				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(CRITICAL_ERROR, 'Could not update user theme info');
				}
			}
			else
			{
				message_die(CRITICAL_ERROR, "Could not get theme data for themes_id [$style]");
			}
		}
		else
		{
			message_die(CRITICAL_ERROR, "Could not get theme data for themes_id [$style]");
		}
	}

	$template_path = 'templates/';
	$template_name = $non_admin_template_name = $row['template_name'];

### R3-born - ADD (Global Admin Templates)
#
	// Force the path to the smilies because the ACP doesn't have any smilies images.
	$images['smiles'] = $root_path . $template_path . $template_name . '/images/smiles';

	if(defined('IN_ADMIN'))
	{
		$template_name = 'admin';
	}
#
### R3-born - END

	$template = new Template($root_path . $template_path . $template_name);

	if ( $template )
	{

		$current_template_path = $template_path . $template_name;
		$current_non_admin_template_path = $template_path . $non_admin_template_name;

		if ( file_exists($root_path . $current_template_path . '/' . $template_name . '.cfg') )
		{
			@include($root_path . $template_path . $template_name . '/' . $template_name . '.cfg');
		}

		if ( !defined('TEMPLATE_CONFIG') )
		{
			message_die(CRITICAL_ERROR, "Could not open $template_name template config file", '', __LINE__, __FILE__);
		}

### R3-born ADD (Module Engine)
#
		// whip through the modules and include any template config files and CSS for all enabled modules.
		foreach	($mvModules as $name =>	$value)
		{
			if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
			{
				if ( file_exists($root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/' . $template_name . '.cfg') )
				{
					$current_template_images = $root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/images';
        			@include($root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/' . $template_name . '.cfg');

				}

				if ( file_exists($root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/' . $template_name . '.css') )
				{
					//$current_template_images = $root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/images';
        			//@include($root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/' . $template_name . '.cfg');
					$mvCSS[$value['module_name']] = $root_path . 'modules/' . $value['module_name'] . '/' . $current_template_path . '/' . $template_name . '.css';
				}

				// If we are in the ACP of a module, check to see if it has a template '.cfg' and include it
				// to get any images which the ACP might need. For example, rank images in the Forum module
				// are displayed in the ACP
				if ( defined('IN_ADMIN') && file_exists($root_path . 'modules/' . $value['module_name'] . '/' . $current_non_admin_template_path . '/' . $non_admin_template_name . '.cfg') )
				{
					$current_template_images = $root_path . 'modules/' . $value['module_name'] . '/' . $current_non_admin_template_path . '/images';
					@include($root_path . 'modules/' . $value['module_name'] . '/' . $current_non_admin_template_path . '/' . $non_admin_template_name . '.cfg');
				}

			}
		}
#
### R3-born - END ADD

		$img_lang = ( file_exists(@realpath($root_path . $current_template_path . '/images/lang_' . $config['default_lang'])) ) ? $config['default_lang'] : 'english';

		while( list($key, $value) = @each($images) )
		{
			if ( !is_array($value) )
			{
				$images[$key] = str_replace('{LANG}', 'lang_' . $img_lang, $value);
			}
		}
	}

	return $row;
}

function encode_ip($dotquad_ip)
{
	$ip_sep = explode('.', $dotquad_ip);
	return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
	$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
	return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}

//
// Create date/time from format and timezone
//
function create_date($format, $gmepoch, $tz)
{
	global $config, $lang, $userdata;
	static $translate;

	if ( empty($translate) && $config['default_lang'] != 'english' )
	{
		@reset($lang['datetime']);
		while ( list($match, $replace) = @each($lang['datetime']) )
		{
			$translate[$match] = $replace;
		}
	}

### R3-born - CHANGE (Daylight Savings)
#
	//return ( !empty($translate) ) ? strtr(@gmdate($format, $gmepoch + (3600 * $tz)), $translate) : @gmdate($format, $gmepoch + (3600 * $tz));

	if($userdata['user_dst'] != 0)
    {
		return ( !empty($translate) ) ? strtr(@gmdate($format, $gmepoch + (3600 * $tz) + (date('I') * 3600)), $translate) : @gmdate($format, $gmepoch + (3600 * $tz) + (date('I') * 3600));
    }
    else
    {
		return ( !empty($translate) ) ? strtr(@gmdate($format, $gmepoch + (3600 * $tz)), $translate) : @gmdate($format, $gmepoch + (3600 * $tz));
    }
#
### R3-born - END CHANGE
}

//
// Pagination routine, generates
// page number sequence
//
function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE)
{
	global $lang;

	$total_pages = ceil($num_items/$per_page);

	if ( $total_pages == 1 )
	{
		return '';
	}

### R3-born - ADD (Fix Wrong Pagination Number MOD)
#
	if ( !( $num_items > 0 ) )
	{
		return '';
	}
#
### R3-born - END ADD

	$on_page = floor($start_item / $per_page) + 1;

	$page_string = '';
	if ( $total_pages > 10 )
	{
		$init_page_max = ( $total_pages > 3 ) ? 3 : $total_pages;

		for($i = 1; $i < $init_page_max + 1; $i++)
		{
			$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '">' . $i . '</a>';
			if ( $i <  $init_page_max )
			{
				$page_string .= ", ";
			}
		}

		if ( $total_pages > 3 )
		{
			if ( $on_page > 1  && $on_page < $total_pages )
			{
				$page_string .= ( $on_page > 5 ) ? ' ... ' : ', ';

				$init_page_min = ( $on_page > 4 ) ? $on_page : 5;
				$init_page_max = ( $on_page < $total_pages - 4 ) ? $on_page : $total_pages - 4;

				for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
				{
					$page_string .= ($i == $on_page) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '">' . $i . '</a>';
					if ( $i <  $init_page_max + 1 )
					{
						$page_string .= ', ';
					}
				}

				$page_string .= ( $on_page < $total_pages - 4 ) ? ' ... ' : ', ';
			}
			else
			{
				$page_string .= ' ... ';
			}

			for($i = $total_pages - 2; $i < $total_pages + 1; $i++)
			{
				$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>'  : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '">' . $i . '</a>';
				if( $i <  $total_pages )
				{
					$page_string .= ", ";
				}
			}
		}
	}
	else
	{
		for($i = 1; $i < $total_pages + 1; $i++)
		{
			$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '">' . $i . '</a>';
			if ( $i <  $total_pages )
			{
				$page_string .= ', ';
			}
		}
	}

	if ( $add_prevnext_text )
	{
		if ( $on_page > 1 )
		{
			$page_string = ' <a href="' . append_sid($base_url . "&amp;start=" . ( ( $on_page - 2 ) * $per_page ) ) . '">' . $lang['Previous'] . '</a>&nbsp;&nbsp;' . $page_string;
		}

		if ( $on_page < $total_pages )
		{
			$page_string .= '&nbsp;&nbsp;<a href="' . append_sid($base_url . "&amp;start=" . ( $on_page * $per_page ) ) . '">' . $lang['Next'] . '</a>';
		}

	}

### R3-born - ADD (Pagination Select List & Input Box)
#
	if ( $total_pages > 10 )
	{
		if ( $total_pages < 100 )
		{
			$select_list = '<select onChange="if (this.options[this.selectedIndex].value != -1) { window.location.href = this.options[this.selectedIndex].value; }">';

			for ($i = 1; $i <= $total_pages; $i++)
			{
				$select_list .= '<option value="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '"' . ( ( $i == $on_page ) ? ' selected="selected"' : '' ) . '>' . $i . '</option>';
			}

			$select_list .= '</select> ';
			$input_box = '';
		}
		else
		{
			$input_box = '<input type="text" size="4" value="'.$on_page.'" onKeyPress="var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; if ( keyCode == 13 ) { var page_no = parseInt(this.value, 10); if ( !isNaN(page_no) && page_no <= '.$total_pages.' && page_no > 0) { var start = String((page_no - 1)*'.$per_page.'); window.location.href = \'' . append_sid($base_url . '&amp;start=\'+start+\'') . '\'; return false;} else { this.value = '.$on_page.'; return false;} }" /> ';
			$select_list = '';
		}
	}
	else
	{
		$input_box = '';
		$select_list = '';
	}

	$page_string = $input_box . $select_list . $page_string;
#
### R3-born - END ADD

	$page_string = $lang['Goto_page'] . ' ' . $page_string;

	return $page_string;
}

//
// This does exactly what preg_quote() does in PHP 4-ish
// If you just need the 1-parameter preg_quote call, then don't bother using this.
//
/*function r3born_preg_quote($str, $delimiter)
{
	$text = preg_quote($str);
	$text = str_replace($delimiter, '\\' . $delimiter, $text);

	return $text;
}*/

//
// Obtain list of naughty words and build preg style replacement arrays for use by the
// calling script, note that the vars are passed as references this just makes it easier
// to return both sets of arrays
//
function obtain_word_list(&$orig_word, &$replacement_word)
{
	global $db;

	static $orig_words, $replacement_words;

	//If we haven't already grabbed this data previously go and get it.
	if( !isset($orig_words) || !isset($replacement_words) )
	{
		//
		// Define censored word matches
		//
		$orig_words = array();
		$replacement_words = array();

		$sql = "SELECT word, replacement
			FROM  " . WORDS_TABLE;
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not get censored words from database', '', __LINE__, __FILE__, $sql);
		}

		if ( $row = $db->sql_fetchrow($result) )
		{
			do
			{
				$orig_words[] = '#\b(' . str_replace('\*', '\w*?', preg_quote($row['word'], '#')) . ')\b#i';
				$replacement_words[] = $row['replacement'];
			}
			while ( $row = $db->sql_fetchrow($result) );
		}

		$orig_word = $orig_words;
		$replacement_word = $replacement_words;

		return true;
	}
	else
	{
		$orig_word = $orig_words;
		$replacement_word = $replacement_words;

		return true;
	}
}

//
// This is general replacement for die(), allows templated
// output in users (or default) language, etc.
//
// $msg_code can be one of these constants:
//
// GENERAL_MESSAGE : Use for any simple text message, eg. results
// of an operation, authorisation failures, etc.
//
// GENERAL ERROR : Use for any error which occurs _AFTER_ the
// common.php include and session code, ie. most errors in
// pages/functions
//
// CRITICAL_MESSAGE : Used when basic config data is available but
// a session may not exist, eg. banned users
//
// CRITICAL_ERROR : Used when config data cannot be obtained, eg
// no database connection. Should _not_ be used in 99.5% of cases
//
function message_die($msg_code, $msg_text = '', $msg_title = '', $err_line = '', $err_file = '', $sql = '')
{
	global $db, $template, $config, $theme, $lang, $phpEx, $root_path, $images;
	global $userdata, $user_ip, $session_length;
	//global $starttime;

### R3-born - ADD (Fix message_die for multiple errors MOD)
#
	static $msg_history;
	if( !isset($msg_history) )
	{
		$msg_history = array();
	}
	$msg_history[] = array(
		'msg_code'	=> $msg_code,
		'msg_text'	=> $msg_text,
		'msg_title'	=> $msg_title,
		'err_line'	=> $err_line,
		'err_file'	=> $err_file,
		'sql'		=> $sql
	);
#
### R3-born - END ADD

	if(defined('HAS_DIED'))
	{
### R3-born - REMOVE
#
//		die("message_die() was called multiple times. This isn't supposed to happen. Was message_die() used in page_tail.php?");
#
### R3-born - END REMOVE

### R3-born - ADD (Fix message_die for multiple errors MOD)
#
		//
		// This message is printed at the end of the report.
		// Of course, you can change it to suit your own needs. ;-)
		//
		$custom_error_message = 'Please, contact the %swebmaster%s. Thank you.';
		if ( !empty($config) && !empty($config['board_email']) )
		{
			$custom_error_message = sprintf($custom_error_message, '<a href="mailto:' . $config['board_email'] . '">', '</a>');
		}
		else
		{
			$custom_error_message = sprintf($custom_error_message, '', '');
		}
		echo "<html>\n<body>\n<b>Critical Error!</b><br />\nmessage_die() was called multiple times.<br />&nbsp;<hr />";
		for( $i = 0; $i < count($msg_history); $i++ )
		{
			echo '<b>Error #' . ($i+1) . "</b>\n<br />\n";
			if( !empty($msg_history[$i]['msg_title']) )
			{
				echo '<b>' . $msg_history[$i]['msg_title'] . "</b>\n<br />\n";
			}
			echo $msg_history[$i]['msg_text'] . "\n<br /><br />\n";
			if( !empty($msg_history[$i]['err_line']) )
			{
				echo '<b>Line :</b> ' . $msg_history[$i]['err_line'] . '<br /><b>File :</b> ' . $msg_history[$i]['err_file'] . "</b>\n<br />\n";
			}
			if( !empty($msg_history[$i]['sql']) )
			{
				echo '<b>SQL :</b> ' . $msg_history[$i]['sql'] . "\n<br />\n";
			}
			echo "&nbsp;<hr />\n";
		}
		echo $custom_error_message . '<hr /><br clear="all">';
		die("</body>\n</html>");
#
### R3-born - END ADD
	}

	define('HAS_DIED', 1);


	$sql_store = $sql;

	//
	// Get SQL error if we are debugging. Do this as soon as possible to prevent
	// subsequent queries from overwriting the status of sql_error()
	//
	if ( DEBUG && ( $msg_code == GENERAL_ERROR || $msg_code == CRITICAL_ERROR ) )
	{
		$sql_error = $db->sql_error();

		$debug_text = '';

		if ( $sql_error['message'] != '' )
		{
			$debug_text .= '<br /><br />SQL Error : ' . $sql_error['code'] . ' ' . $sql_error['message'];
		}

		if ( $sql_store != '' )
		{
			$debug_text .= "<br /><br />$sql_store";
		}

		if ( $err_line != '' && $err_file != '' )
		{
			$debug_text .= '<br /><br />Line : ' . $err_line . '<br />File : ' . basename($err_file);
		}
	}

	if( empty($userdata) && ( $msg_code == GENERAL_MESSAGE || $msg_code == GENERAL_ERROR ) )
	{
		// If init_userprefs(); hasn't been called then we need to clear down the $mv*** vars otherwise the wrong page id will be substituted by the module API.
		global $mvModuleTemplates, $mvModuleName, $mvModuleFile, $mvModule_root_path;

		$mvModuleTemplates = array();
		$mvModuleName =	'';
		$mvModuleFile =	'';
		$mvModule_root_path = '';

		$userdata = session_pagestart($user_ip, PAGE_INDEX);
		init_userprefs($userdata);
	}

	//
	// If the header hasn't been output then do it
	//
	if ( !defined('HEADER_INC') && $msg_code != CRITICAL_ERROR )
	{
		if ( empty($lang) )
		{
			if ( !empty($config['default_lang']) )
			{
				include($root_path . 'language/lang_' . $config['default_lang'] . '/lang_main.'.$phpEx);
			}
			else
			{
				include($root_path . 'language/lang_english/lang_main.'.$phpEx);
			}
		}

		if ( empty($template) || empty($theme) )
		{
			$theme = setup_style($config['default_style']);
		}

		//
		// Load the Page Header
		//
		if ( !defined('IN_ADMIN') )
		{
			page_header();
		}
		else
		{
			include_once($root_path . 'includes/functions_admin.' . $phpEx);
			page_header_admin();
		}
	}

	switch($msg_code)
	{
		case GENERAL_MESSAGE:
			if ( $msg_title == '' )
			{
				$msg_title = $lang['Information'];
			}
			break;

		case CRITICAL_MESSAGE:
			if ( $msg_title == '' )
			{
				$msg_title = $lang['Critical_Information'];
			}
			break;

		case GENERAL_ERROR:
			if ( $msg_text == '' )
			{
				$msg_text = $lang['An_error_occured'];
			}

			if ( $msg_title == '' )
			{
				$msg_title = $lang['General_Error'];
			}
			break;

		case CRITICAL_ERROR:
			//
			// Critical errors mean we cannot rely on _ANY_ DB information being
			// available so we're going to dump out a simple echo'd statement
			//
			include($root_path . 'language/lang_english/lang_main.'.$phpEx);

			if ( $msg_text == '' )
			{
				$msg_text = $lang['A_critical_error'];
			}

			if ( $msg_title == '' )
			{
				$msg_title = 'R3-born : <b>' . $lang['Critical_Error'] . '</b>';
			}
			break;
	}

	//
	// Add on DEBUG info if we've enabled debug mode and this is an error. This
	// prevents debug info being output for general messages should DEBUG be
	// set TRUE by accident (preventing confusion for the end user!)
	//
	if ( DEBUG && ( $msg_code == GENERAL_ERROR || $msg_code == CRITICAL_ERROR ) )
	{
		if ( $debug_text != '' )
		{
			$msg_text = $msg_text . '<br /><br /><b><u>DEBUG MODE</u></b>' . $debug_text;
		}
	}

	if ( $msg_code != CRITICAL_ERROR )
	{
		if ( !empty($lang[$msg_text]) )
		{
			$msg_text = $lang[$msg_text];
		}

		if ( !defined('IN_ADMIN') )
		{
			$template->set_filenames(array(
				'message_body' => 'message_body.tpl')
			);
		}
		else
		{
### R3-born - REMOVE (Original Code)
#
/*
			$template->set_filenames(array(
				'message_body' => 'admin/admin_message_body.tpl')
			);
*/
#
### R3-born - END REMOVE

### R3-born - ADD (Global Admin Template)
#
			$template->set_filenames(array(
				'message_body' => 'admin_message_body.tpl')
			);
#
### R3-born - END ADD
		}

		$template->assign_vars(array(
			'MESSAGE_TITLE' => $msg_title,
			'MESSAGE_TEXT' => $msg_text)
		);
		$template->pparse('message_body');

		if ( !defined('IN_ADMIN') )
		{
			page_footer();
		}
		else
		{
			page_footer_admin();
		}
	}
	else
	{
		echo "<html>\n<body>\n" . $msg_title . "\n<br /><br />\n" . $msg_text . "</body>\n</html>";
	}

	exit;
}

function redirect($url)
{
	global $db, $config, $lang;

	if (!empty($db))
	{
		$db->sql_close();
	}

	if (strstr(urldecode($url), "\n") || strstr(urldecode($url), "\r") || strstr(urldecode($url), ';url')) //phpbb 2.0.22 fix
	{
		message_die(GENERAL_ERROR, 'Tried to redirect to potentially insecure url.');
	}

	//$url = preg_replace('#^\/?(.*?)\/?$#', '/\1', trim($url)); // Broken - Add an extra /
	$url = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($url)); // Fixed

	// Redirect via an HTML form for PITA webservers
	if (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')))
	{
		header('Refresh: 0; URL=' . generate_website_url() . $url);
		echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset='. $lang['ENCODING'].'"><meta http-equiv="refresh" content="0; url=' . generate_website_url() . $url . '"><title>Redirect</title></head><body><div align="center">If your browser does not support meta redirection please click <a href="' . generate_website_url() . $url . '">HERE</a> to be redirected</div></body></html>';
		exit;
	}

	// Behave as per HTTP/1.1 spec for others
	header('Location: ' . generate_website_url() . $url);
	exit;
}

if(!function_exists('htmlspecialchars_decode'))
{
	function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
	{
		return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
	}
}

/**
* _set_var
*
* Set variable, used by {@link get_var the get_var function}
*
* @private
**/
function _set_var(&$result, $var, $type, $multibyte = false)
{
	settype($var, $type);
	$result = $var;

	if ($type == 'string')
	{
		$result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result)));
		// R3-born is doing addslashes on all variables, so we now need to strip them.
		$result = stripslashes($result);

		// Check for possible multibyte characters to save a preg_replace call if nothing is in there...
		if ($multibyte && strpos($result, '&amp;#') !== false)
		{
			$result = preg_replace('#&amp;(\#[0-9]+;)#', '&\1', $result);
		}
	}
}

/**
* get_var
*
* Used to get passed variable
**/
function get_var($var_name, $default, $multibyte = false)
{
	$request_var = (isset($_POST[$var_name])) ? $_POST : $_GET;

	if (!isset($request_var[$var_name]) || (is_array($request_var[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($request_var[$var_name])))
	{
		return (is_array($default)) ? array() : $default;
	}

	$var = $request_var[$var_name];

	if (!is_array($default))
	{
		$type = gettype($default);
	}
	else
	{
		list($key_type, $type) = each($default);
		$type = gettype($type);
		$key_type = gettype($key_type);
	}

	if (is_array($var))
	{
		$_var = $var;
		$var = array();

		foreach ($_var as $k => $v)
		{
			if (is_array($v))
			{
				foreach ($v as $_k => $_v)
				{
					_set_var($k, $k, $key_type);
					_set_var($_k, $_k, $key_type);
					_set_var($var[$k][$_k], $_v, $type, $multibyte);
				}
			}
			else
			{
				_set_var($k, $k, $key_type);
				_set_var($var[$k], $v, $type, $multibyte);
			}
		}
	}
	else
	{
		_set_var($var, $var, $type, $multibyte);
	}

	return $var;
}

// retrun an array of group_id that a user is a member of.
function obtain_users_groups($user_id)
{
	global $db, $userdata;

	static $users_groups;

	if(!isset($users_groups))
	{
		$sql = "SELECT group_id FROM " . USER_GROUP_TABLE . " WHERE user_id = '" . $user_id . "' AND user_pending = 0";
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, "Could not query user group information", "", __LINE__, __FILE__, $sql);
		}

		while ($row = $db->sql_fetchrow($result))
		{
			$users_groups[] = intval($row['group_id']);
		}
		$db->sql_freeresult($result);
	}

	return $users_groups;
}

function obtain_color_groups()
{
	global $db, $config, $userdata;

	$groupdata = array();
	$rows = array();
	$group_users = array();

	$staff_sql = ($userdata['user_level'] == USER) ? 'AND g.group_type <> ' . GROUP_HIDDEN : '';

	$sql = "SELECT g.group_name, g.group_colors, ug.group_id, u.username, u.user_id, u.group_priority
			FROM " . GROUPS_TABLE . " g, " . USER_GROUP_TABLE . " ug, " . USERS_TABLE . " u
			WHERE g.group_single_user != 1
			AND g.group_colored <> 0
			AND ug.user_pending = 0
			AND ug.group_id = g.group_id
			AND ug.user_id = u.user_id
			$staff_sql
			ORDER BY g.group_order, g.group_name";
	if ( ! $result = $db->sql_query($sql) )
	{
		message_die(GENERAL_ERROR, 'Could not get group data from database', '', __LINE__, __FILE__, $sql);
	}
	while ( $row = $db->sql_fetchrow($result) )
	{
		$row['group_colors'] = unserialize($row['group_colors']);
		$rows[] = $row;
	}
	for($i = 0; $i < sizeof($rows); $i++)
	{
		$groupdata['userdata'][ $rows[$i]['user_id'] ] = array(
			'user_id' => $rows[$i]['user_id'],
			'username' => $rows[$i]['username'],
			'group_priority' => $rows[$i]['group_priority'],
		);
		$group_users[ $rows[$i]['group_id'] ][ $rows[$i]['user_id'] ] = $rows[$i]['user_id'];
		$groupdata['groupdata'][ $rows[$i]['group_id'] ] = array(
			'group_id' => $rows[$i]['group_id'],
			'group_color' => $rows[$i]['group_colors'],
			'group_name' => $rows[$i]['group_name'],
			'group_users' => $group_users[ $rows[$i]['group_id'] ],
		);
	}
	return $groupdata;
}

function color_groups_user($user_id)
{
	global $userdata, $color_groups, $config;

	if ( ! $color_groups )
	{
		return false;
	}
	if ( ! is_array($color_groups['groupdata']) )
	{
		return false;
	}
	foreach ( $color_groups['groupdata'] AS $group_data )
	{
		if ( ! $userdata['session_logged_in'] )
		{
			$group_color = $group_data['group_color'][ $config['default_style'] ];
		}
		else
		{
			$group_color = $group_data['group_color'][ $userdata['user_style'] ];
		}
		if ( ! $group_color )
		{
			$match_found = false;
			foreach ( $group_data['group_color'] AS $color )
			{
				if ( ! $match_found )
				{
					if ( $color )
					{
						$group_color = $color;
						$match_found = true;
					}
				}
			}
		}
		if ( $color_groups['userdata'][$user_id]['group_priority'] == $group_data['group_id'] || ! $color_groups['userdata'][$user_id]['group_priority'] )
		{
			if ( in_array ( $user_id, $group_data['group_users'] ) )
			{
				return $group_color;
			}
		}
	}
	return false;
}

function color_groups_group($group_id)
{
	global $userdata, $color_groups, $config;

	if ( is_array($color_groups['groupdata']) )
	{
		$group_data = $color_groups['groupdata'][$group_id];
		if ( is_array($group_data) )
		{
				if ( ! $userdata['session_logged_in'] )
				{
					$group_color = $group_data['group_color'][ $config['default_style'] ];
				}
				else
				{
					$group_color = $group_data['group_color'][ $userdata['user_style'] ];
				}
				if ( ! $group_color )
				{
					$match_found = false;
					foreach ( $group_data['group_color'] AS $color )
					{
						if ( ! $match_found )
						{
							if ( $color )
							{
								$group_color = $color;
								$match_found = true;
							}
						}
					}
				}
				if ( $group_color )
				{
					return $group_color;
				}
		}
	}
	return false;
}

function color_user($user_id, $username, $profile_link = false)
{
	global $lang, $phpEx;

	static $last_user_id, $style_color;

	if ( (!isset($last_user_id) || !isset($style_color)) || (isset($last_user_id) && ($last_user_id != $user_id)) )
	{
		$style_color = ($user_color = color_groups_user($user_id)) ? ' style="font-weight:bold;color:#' . $user_color . '" ' : '';
	}

	if ($profile_link)
	{
		$color_me = ( $user_id != ANONYMOUS ) ? '<a href="' . append_sid('profile.' . $phpEx . '?mode=viewprofile&amp;' . POST_USERS_URL . '=' . $user_id) . '" ' . $style_color . '>' : '';
		$color_me .= ( $user_id != ANONYMOUS ) ? $username : ( ( $username != '' ) ? $username : $lang['Guest'] );
		$color_me .= ( $user_id != ANONYMOUS ) ? '</a>' : '';
	}
	else
	{
		$color_me = '<span' . $style_color . '>' . $username . '</span>';
	}

	$last_user_id = $user_id;

	return $color_me;
}

function get_policy($policy_id = 0, $what = 'text')
{
    global $db;

    static $policy = '';

    if (!is_array($policy) )
    {
    	$sql = "SELECT * FROM " . POLICY_TABLE . " ORDER BY policy_id";

		if( !($result = $db->sql_query($sql)) )
        {
        	message_die(GENERAL_ERROR, 'Could not obtain the policies', '', __LINE__, __FILE__, $sql);
        }

        $policy = array();

		while ($row = $db->sql_fetchrow($result))
        {
        	$policy[$row['policy_id']] = array(
        	        'NAME'  => $row['policy_name'],
                    'TEXT'  => $row['policy_text'],
                    'DATE'  => $row['policy_date']
                );
        }

	    $db->sql_freeresult($result);
    }

    if ( isset($policy[$policy_id]) )
    {
        $what = strtoupper($what);

        if ($what == 'NAME' || $what == 'TEXT' || $what == 'DATE')
        {
            return $policy[$policy_id][$what];
        }
        else
        {
            return $policy[$policy_id];
        }
    }

    return FALSE;
}

function jr_admin_get_user_info($user_id)
{
    global $lang, $db;

	$sql = 'SELECT * FROM ' . JR_ADMIN_TABLE . ' WHERE user_id = ' . $user_id;
	if ( !($result = $db->sql_query($sql)) )
	{
		messsage_die (GENERAL_ERROR, sprintf($lang['Error_Table'], JR_ADMIN_TABLE), '', __LINE__, __FILE__, $sql);
	}

	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	return $row;
}

function jr_admin_user_exist($user_id)
{
	global $db, $lang;

	$sql = 'SELECT start_date FROM ' . JR_ADMIN_TABLE . ' WHERE user_id = ' . $user_id;
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, $lang['Error_Module_Table'], '', __LINE__, __FILE__, $sql);
	}

	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

    return isset($row['start_date']);
}

function jr_admin_make_admin_link()
{
    global $lang, $userdata, $phpEx;

	$admin_link = '<a href="admin/index.' . $phpEx . '?sid=' . $userdata['session_id'] . '">' . $lang['Admin_panel'] . '</a>';

	// Breaking the logic up in this way results in an optimization is no Jnr. Admins are
	// defined since the DB lookups don't get made.'
	if ( $userdata['user_level'] == ADMIN)
	{
		return $admin_link;
	}
	elseif ( jr_admin_user_exist($userdata['user_id']) )
	{
		return $admin_link;
	}
	else
	{
		return '';
	}
}

/**
* Generate board url (example: http://www.foo.bar/site)
* @param bool $without_script_path if set to true the script path gets not appended (example: http://www.foo.bar)
*/
function generate_website_url($script_file = '', $without_script_path = false)
{
	global $config;

	$server_name = trim($config['server_name']);
	$server_port = $config['server_port'];
	$url = (($config['cookie_secure']) ? 'https://' : 'http://') . $server_name;
	if ($server_port && (($config['cookie_secure'] && $server_port <> 443) || (!$config['cookie_secure'] && $server_port <> 80)))
	{
		$url .= ':' . $server_port;
	}

	if ($without_script_path)
	{
		str_replace('//', '/', $url);
		return $url;
	}

	//$script_path = preg_replace('/^\/?(.*?)\/?$/', "\\1", trim($config['script_path']));
	$script_path = trim($config['script_path']);

	if ($script_file != '')
	{
		//$script_path = ( $script_path != '' ) ? $script_path . '/' . $script_file : $script_file;
		$script_path = ( $script_path != '' ) ? $script_path . $script_file : $script_file;
	}

	$url .= $script_path;
	str_replace('//', '/', $url);
	return $url;

}

function page_header($page_title = '', $gen_simple_header = false)
{
	global $config, $template, $userdata, $root_path, $phpEx, $lang, $theme, $db;
	global $mvModules, $mvModuleName, $mvModuleFile, $mvLayoutName, $mvCSS;

	define('HEADER_INC', true);

	//
	//gzip_compression
	//
	if ( $config['gzip_compress'] && extension_loaded('zlib') )
	{
		ob_start('ob_gzhandler');
	}

	//
	// 	Parse and show the overall header.
	//
	$template->set_filenames(array(
		'overall_header' => ($gen_simple_header) ? 'simple_header.tpl' : 'overall_header.tpl')
	);





	if ( !$userdata['session_logged_in'] )
	{
	ob_start(); 
	}





	//
	//Generate logged in/logged out status
	//
	if ( $userdata['session_logged_in'] )
	{
		$u_login_logout = 'login.'.$phpEx.'?logout=true&amp;sid=' . $userdata['session_id'];
		$l_login_logout = $lang['Logout'] . ' [ ' . $userdata['username'] . ' ]';
	}
	else
	{
		$u_login_logout = 'login.'.$phpEx;
		$l_login_logout = $lang['Login'];
	}

	$s_last_visit = ( $userdata['session_logged_in'] ) ? create_date($config['default_dateformat'], $userdata['user_lastvisit'], $config['board_timezone']) : '';

	// Format Timezone. We are unable to use array_pop here, because of PHP3 compatibility
	$l_timezone = explode('.', $config['board_timezone']);
	$l_timezone = (count($l_timezone) > 1 && $l_timezone[count($l_timezone)-1] != 0) ? $lang[sprintf('%.1f', $config['board_timezone'])] : $lang[number_format($config['board_timezone'])];

### R3-born - ADD (Registration Stopper)
#
	if ( $config['registrations_accept'] && !$userdata['session_logged_in'] )
	{
		$template->assign_block_vars('switch_register', array());
	}
#
### END ADD

	//
	// 	The following assigns all _common_ variables that may be used at any point
	// 	in a template.
	//
	include_javascript('lib_bbcode.js'); //Ideally, this could be moved so it is only included when bbcodes are being parsed.

	$template->assign_vars(array(
		'SITENAME' => $config['sitename'],
		'SITE_DESCRIPTION' => $config['site_desc'],
		'PAGE_TITLE' => $page_title,

### R3-born - ADD (META Tags)
#
		'META_LANGUAGE' => $config['meta_language'],
    	'META_AUTHOR' => $config['meta_author'],
    	'META_KEYWORDS' => $config['meta_keywords'],
    	'META_DESCRIPTION' => $config['meta_description'],
    	'META_ROBOTS' => $config['meta_robots'],
    	'META_RATING' => $config['meta_rating'],
    	'META_VISIT_AFTER' => $config['meta_visit_after'],
#
### R3-born - END ADD

		'LAST_VISIT_DATE' => sprintf($lang['You_last_visit'], $s_last_visit),
		'CURRENT_TIME' => sprintf($lang['Current_time'], create_date($config['default_dateformat'], time(), $config['board_timezone'])),
		'L_USERNAME' => $lang['Username'],
		'L_PASSWORD' => $lang['Password'],
		'L_LOGIN_LOGOUT' => $l_login_logout,
		'L_LOGIN' => $lang['Login'],
		'L_LOG_ME_IN' => $lang['Log_me_in'],
		'L_AUTO_LOGIN' => $lang['Log_me_in'],
    	'L_INDEX' => $lang['Home'],
		'L_REGISTER' => $lang['Register'],
		'L_VISITED' => $lang['Visited'],
		'L_PROFILE' => $lang['Profile'],
		'L_SEARCH' => $lang['Search'],
		'L_HELP' => $lang['Help'],
		'L_USERGROUPS' => $lang['Usergroups'],
		'U_INDEX' => append_sid('index.'.$phpEx),
		'U_REGISTER' => append_sid('register.'.$phpEx),
		'U_PROFILE' => append_sid('profile.'.$phpEx.'?mode=editprofile'),
		'U_SEARCH' => append_sid('search.'.$phpEx),
		'U_HELP' => append_sid('help.'.$phpEx),
		'U_LOGIN_LOGOUT' => append_sid($u_login_logout),
		'U_GROUP_CP' => append_sid('groupcp.'.$phpEx),
		'U_PNGFIX_JS' => $root_path . 'javascript/pngfix.js',

		'S_CONTENT_DIRECTION' => $lang['DIRECTION'],
		'S_CONTENT_ENCODING' => $lang['ENCODING'],
		'S_CONTENT_DIR_LEFT' => $lang['LEFT'],
		'S_CONTENT_DIR_RIGHT' => $lang['RIGHT'],
		'S_TIMEZONE' => sprintf($lang['All_times'], $l_timezone),
		'S_LOGIN_ACTION' => append_sid('login.'.$phpEx),

		'STYLESHEET' => $theme['head_stylesheet'],
		)
	);

### R3-born - ADD (Jnr. Admin)
#
	$admin_link = jr_admin_make_admin_link();

	if ($admin_link != '')
	{
		$template->assign_vars(array(
			'ADMIN_LINK' => $admin_link
			)
		);
	}
#
### R3-born - END ADD

	//
	// 	Set user logged in/out switches
	//
	if ( !$userdata['session_logged_in'] )
	{
		$template->assign_block_vars('switch_user_logged_out', array());
		//
		// Allow autologin?
		//
		if (!isset($config['allow_autologin']) || $config['allow_autologin'] )
		{
			$template->assign_block_vars('switch_allow_autologin', array());
			$template->assign_block_vars('switch_user_logged_out.switch_allow_autologin', array());
		}
	}
	else
	{
		$template->assign_block_vars('switch_user_logged_in', array());
	}

### R3-born - ADD (Site disabled excluding Admins)
#
	// If disabled and admin, show Reminder Box below header and warn if the 'install' directory is still there.
	if ( $config['board_disable'] && $userdata['user_level'] == ADMIN )
	{
		$message = '';

		$template->set_filenames(array('warning' => 'warning_body.tpl'));

		if ($config['board_disable'] && $userdata['user_level'] == ADMIN)
		{
			$message .= $config['board_disable_text'] ? $config['board_disable_text'] . '<br />' : $lang['Board_disable'] . '<br />';
		}

		/*if (file_exists('install'))
		{
			$message .= $lang['Please_remove_install'] . '<br />';
		}*/

		$template->assign_vars(array('WARNING_MESSAGE' => $message));
		$template->assign_var_from_handle('WARNING', 'warning');
	}

#
### R3-born - END ADD

### R3-born - ADD (Module Engine)
#
    //include mvHeaders.php for each enabled module, but not when in the ACP
	if ( !empty($mvModules) && !defined('IN_ADMIN') )
	{
		foreach	($mvModules as $name =>	$value)
		{
			if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
			{
				foreach	($value['headers'] as $n => $file)
				{
					@include($root_path . 'modules/' .	$name .	'/'	. $file);
				}
			}
		}
	}

	//Includes any block/module content style sheets, but not when in the ACP or when usigna simple header.
	if ( !empty($mvCSS) && !defined('IN_ADMIN') && !$gen_simple_header)
	{
		foreach	($mvCSS as $name =>	$value)
		{
			$template->assign_block_vars('css',array(
				'INCLUDE' => $value
				)
			);
		}
	}

#
### R3-born - END ADD

	header('Cache-Control: private, no-cache="set-cookie", pre-check=0, post-check=0');
	header('Expires: 0');
	header('Pragma: no-cache');

	// Workout the full URL from the module name and file to determine what
	// layout should be used.
	if (!$gen_simple_header)
	{

		// Are we accessing a module or just the root index.php with no module specified?
		if ( ($mvModuleName != '' && $mvModuleFile != '') && (strpos($_SERVER['QUERY_STRING'], $mvModuleName)) )
		{
			$mvLayoutURL = append_sid($mvModuleFile . '.' . $phpEx, false, $mvModuleName);
		}
		else
		{
			$mvLayoutURL = str_replace($config['script_path'], '', $_SERVER['PHP_SELF']);

		}

    	//print $mvLayoutURL . "\n";
    	//print $_SERVER['QUERY_STRING'] . "\n";

		//Get the layout data
		$mvLayout = getLayout($mvLayoutURL);

		// Can this user access pages using this layout?
		// Make sure you can always get to the login page in case someone setup some silly permissions
		if ( access_permitted($mvLayout['layout_view'], $mvLayout['groups']) || defined('IN_LOGIN') )
		{
			parseBlocks($mvLayout['layout_id']);
			$template->pparse('overall_header');
		}
		else
		{
			parseBlocks($config['default_layout']);
			$template->pparse('overall_header');
			message_die(GENERAL_MESSAGE, $lang['Page_denied']);
		}
	}
	else
	{
		$template->pparse('overall_header');
	}
}

function page_footer($gen_simple_header = false)
{
	global $root_path, $phpEx, $lang, $template, $db, $config, $starttime, $userdata;

	//
	// Show the overall footer.
	//
	$temp_url = '<a href="' . append_sid($root_path . "policy.$phpEx?id=%s") . '">%s</a>';
	$copyright = get_policy(COPYRIGHT_POL_ID, 'text');
	$terms = ( get_policy(TERMS_POL_ID, 'text') ) ? sprintf($temp_url, TERMS_POL_ID, $lang['Terms_of_Use']) : '';
	$privacy = ( get_policy(PRIVACY_POL_ID, 'text') ) ? sprintf($temp_url, PRIVACY_POL_ID, $lang['Privacy_Policy']) : '';
	$legal = ( $copyright ) ? $copyright . '<br />' : '';
	$legal .= ( $terms xor $privacy ) ? ($terms . $privacy) : (( $terms && $privacy ) ? ($terms . ' | ' . $privacy) : '');

	$template->set_filenames(array(
		'overall_footer' => ($gen_simple_header) ? 'simple_footer.tpl' : 'overall_footer.tpl')
	);

	$template->assign_vars(array(
		'TRANSLATION_INFO' => (isset($lang['TRANSLATION_INFO'])) ? $lang['TRANSLATION_INFO'] : ((isset($lang['TRANSLATION'])) ? $lang['TRANSLATION'] : ''),
		'LEGAL_INFO'	   => $legal,
		'YEAR'			   => date('Y'),
		)
	);

	//
	// Close our DB connection.
	//
	$db->sql_close();

	if (defined('DEBUG_EXTRA'))
	{

		if (function_exists('memory_get_usage'))
		{
			global $base_memory_usage;

			$memory_usage = memory_get_usage() - $base_memory_usage;
			$memory_usage = ($memory_usage >= 1048576) ? round((round($memory_usage / 1048576 * 100) / 100), 2) . ' ' . $lang['MB'] : (($memory_usage >= 1024) ? round((round($memory_usage / 1024 * 100) / 100), 2) . ' ' . $lang['KB'] : $memory_usage . ' ' . $lang['Bytes']);
		}
		else
		{
			$memory_usage = 'n/a';
		}

		$endtime = microtime();
		$endtime = explode(" ", microtime());
		$endtime = $endtime[1] + $endtime[0];
		$gentime = round(($endtime - $starttime), 3);

		$template->assign_block_vars('switch_debug_extra', array());

		$template->assign_vars(array(
			'L_PAGE_GENERATION_TIME' 	=> sprintf($lang['Page_generation_time'], $gentime),
			'L_DB_QUERIES' 				=> sprintf($lang['DB_queries'], $db->num_queries),
			'TPL_CACHE_HIT_RATIO' 		=> sprintf($lang['TPL_cache_hit_ratio'], round($template->cache_hits*100/($template->cache_misses+$template->cache_hits)+0.00000001,1)),
			'L_GZIP' 					=> ($config['gzip_compress'] && extension_loaded('zlib'))  ? 'gzip : ' . $lang['Enabled'] : 'gzip : ' . $lang['Disabled'],
			'L_MEM_USED' 				=> sprintf($lang['Memory_used'], $memory_usage),
			)
		);
	}

	$template->pparse('overall_footer');


	if ( !$userdata['session_logged_in'] )
	{
	$contents = ob_get_contents(); 
	ob_end_clean();


//------------------------------
/*
	$log = './cache/log.log';

	// Attempt to write out the IPS log data.
	if ($fp = @fopen($log, 'a'))
	{

		$ips_data = $contents;

		@fwrite($fp, $ips_data);
	}
	@fclose($fp);
*/
//------------------------------





 
	echo replace_for_mod_rewrite($contents); 
	//global $dbg_starttime; 
	}
 



	exit;
}

function obtain_config($table = CONFIG_TABLE)
{
	global $db;

	// Get core or module wide config data. If this fails then we output a CRITICAL_ERROR since basic information is not available
	$sql = 'SELECT * FROM ' . $table;
	if( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not query config information from ' . $table, '', __LINE__, __FILE__, $sql);
	}

	while ( $row = $db->sql_fetchrow($result) )
	{
		$config[$row['config_name']] = $row['config_value'];
	}
	$db->sql_freeresult($result);
	return $config;
}

function user_avatar($user_allowavatar, $user_avatar_type, $user_avatar, $size = 0)
{
	global $config, $root_path, $phpEx, $lang;

	$resize = ($size != 0) ? ' width = "' . $size . '"' : '';

	$avatar_img = '';
	if ( $user_avatar_type && $user_allowavatar )
	{
		switch( $user_avatar_type )
		{
			case USER_AVATAR_UPLOAD:
				$avatar_img = ( $config['allow_avatar_upload'] ) ? '<img src="' . $config['avatar_path'] . '/' . $user_avatar . '" alt="' . $lang['Avatar'] . '" border="0" ' . $resize . ' />' : '';
				break;
			case USER_AVATAR_REMOTE:
				$avatar_img = ( $config['allow_avatar_remote'] ) ? '<img src="' . $user_avatar . '" alt="' . $lang['Avatar'] . '" border="0" ' . $resize . ' />' : '';
				break;
			case USER_AVATAR_GALLERY:
				$avatar_img = ( $config['allow_avatar_local'] ) ? '<img src="' . $config['avatar_gallery_path'] . '/' . $user_avatar . '" alt="' . $lang['Avatar'] . '" border="0" ' . $resize . ' />' : '';
				break;
			// Gravatar MOD
			case USER_GRAVATAR:
				include_once($root_path . 'includes/functions_gravatar.'.$phpEx);
				$avatar_img = ($size != 0) ? gravatar_output($user_avatar, $size) : gravatar_output($user_avatar);
				break;
		}
	}
	return $avatar_img;
}

function check_guest_captcha(&$error_msg)
{
	global $config, $db, $userdata, $lang;

	if ( $config['enable_confirm'] && !$userdata['session_logged_in'] )
	{
		if ( empty($_POST['confirm_id']) || empty($_POST['confirm_code']) )
		{
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
		}
		else
		{
			$confirm_id = htmlspecialchars($_POST['confirm_id']);
			if (!preg_match('/^[A-Za-z0-9]+$/', $confirm_id))
			{
				$confirm_id = '';
			}

			$sql = 'SELECT code
					FROM ' . CONFIRM_TABLE . "
					WHERE confirm_id = '$confirm_id'
					AND confirm_type = " . CAPTCHA_POST . "
					AND session_id = '" . $userdata['session_id'] . "'";
			if (!($result = $db->sql_query($sql)))
			{
				message_die(GENERAL_ERROR, 'Could not obtain confirmation code', '', __LINE__, __FILE__, $sql);
			}

			if ($row = $db->sql_fetchrow($result))
			{
				if ($row['code'] != $_POST['confirm_code'])
				{
					$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
				}
				else
				{
					$sql = 'DELETE FROM ' . CONFIRM_TABLE . "
							WHERE confirm_type = " . CAPTCHA_POST . "
							AND session_id = '" . $userdata['session_id'] . "'";
					if (!$db->sql_query($sql))
					{
						message_die(GENERAL_ERROR, 'Could not delete confirmation code', '', __LINE__, __FILE__, $sql);
					}
				}
			}
			else
			{
				$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
			}
			$db->sql_freeresult($result);
		}
	}
}

function display_guest_captcha(&$hidden_form_fields)
{
	global $config, $userdata, $lang, $template, $db, $phpEx, $user_ip;

	$confirm_image = '';
	if (!empty($config['enable_confirm']) && !$userdata['session_logged_in'] )
	{
		$sql = 'SELECT session_id
			FROM ' . SESSIONS_TABLE;
		if (!($result = $db->sql_query($sql)))
		{
			message_die(GENERAL_ERROR, 'Could not select session data', '', __LINE__, __FILE__, $sql);
		}

		if ($row = $db->sql_fetchrow($result))
		{
			$confirm_sql = '';
			do
			{
				$confirm_sql .= (($confirm_sql != '') ? ', ' : '') . "'" . $row['session_id'] . "'";
			}
			while ($row = $db->sql_fetchrow($result));

			$sql = 'DELETE FROM ' .  CONFIRM_TABLE . "
				WHERE session_id NOT IN ($confirm_sql)";
			if (!$db->sql_query($sql))
			{
				message_die(GENERAL_ERROR, 'Could not delete stale confirm data', '', __LINE__, __FILE__, $sql);
			}
		}
		$db->sql_freeresult($result);

		/*$sql = 'SELECT COUNT(session_id) AS attempts
			FROM ' . CONFIRM_TABLE . "
			WHERE session_id = '" . $userdata['session_id'] . "'";
		if (!($result = $db->sql_query($sql)))
		{
			message_die(GENERAL_ERROR, 'Could not obtain confirm code count', '', __LINE__, __FILE__, $sql);
		}

		if ($row = $db->sql_fetchrow($result))
		{
			if ($row['attempts'] > 3)
			{
				message_die(GENERAL_MESSAGE, $lang['Too_many_posts']);
			}
		}
		$db->sql_freeresult($result); */

		// Generate the required confirmation code
		// NB 0 (zero) could get confused with O (the letter) so we make change it
		$code = dss_rand();
		$code = substr(str_replace('0', 'Z', strtoupper(base_convert($code, 16, 35))), 2, 6);

		$confirm_id = md5(uniqid($user_ip));

		$sql = 'INSERT INTO ' . CONFIRM_TABLE . " (confirm_id, session_id, code, confirm_type)
			VALUES ('$confirm_id', '". $userdata['session_id'] . "', '$code', " . CAPTCHA_POST . ")";
		if (!$db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not insert new confirm code information', '', __LINE__, __FILE__, $sql);
		}

		unset($code);

		$confirm_image = '<img src="' . append_sid("register.$phpEx?mode=confirm&amp;id=$confirm_id") . '" alt="" title="" />';
		$hidden_form_fields .= '<input type="hidden" name="confirm_id" value="' . $confirm_id . '" />';

		$template->set_filenames(array(
			'captcha_form' => 'captcha_form.tpl')
		);

		$template->assign_vars(array(
			'CONFIRM_IMG' => $confirm_image,
			'L_CONFIRM_CODE_IMPAIRED'	=> sprintf($lang['Confirm_code_impaired'], '<a href="mailto:' . $config['board_email'] . '">', '</a>'),
			'L_CONFIRM_CODE' => $lang['Confirm_code'],
			'L_CONFIRM_CODE_EXPLAIN' => $lang['Confirm_code_explain']
			)
		);

		$template->assign_var_from_handle('CAPTCHA_FORM', 'captcha_form');
	}
}

//
//Must be called before page_header();
//Includes a javascript library between the <head></head> tags of the page.
function include_javascript($javascript_filename, $module_name = '')
{
	global $root_path, $template;

	$template->set_filenames(array(
		'include_javascript' => 'include_javascript.tpl'
		)
	);

	$javascript_lib = ($module_name == '') ? $root_path . 'javascript/' . $javascript_filename : $root_path . 'modules/' . $module_name . '/javascript/' . $javascript_filename;
	
	$template->assign_vars(array(
		'JAVASCRIPT_LIB' => $javascript_lib
		)
	);

	$template->assign_block_vars('js',array());
	$template->assign_block_var_from_handle('js.INCLUDE', 'include_javascript');
}

//
//Must be called before page_header();
//Includes a javascript library between the <head></head> tags of the page.
function include_livemarks($title, $link, $type = 'rss')
{
	global $template;

	/*switch( $type )
	{
		case LIVEMARK_RSS:
			$lm_type = 'application/rss+xml';
			break;

		case LIVEMARK_ATOM:
			$lm_type = 'application/atom+xml';
			break;
	}*/

	$template->set_filenames(array(
		'include_livemarks' => 'include_livemarks.tpl'
		)
	);

	$template->assign_vars(array(
		'TITLE' => $title,
		'LINK' => $link,
		'TYPE' => 'application/rss+xml'
		)
	);

	$template->assign_block_vars('header',array());
	$template->assign_block_var_from_handle('header.OUTPUT', 'include_livemarks');
}

if (!function_exists('stripos'))
{
	function stripos($haystack, $needle, $offset = 0)
	{
		return strpos(strtolower($haystack), strtolower($needle), $offset);
	}
}

/**
* Determine if user is a search bot
*/
function is_search_bot($user_ip, $user_agent)
{
	global $bot_ip, $bot_agent, $bot_name;

	$bot_ip_match = -1;
	$bot_agent_match = -1;

	//See if the IP matches one in our list of known search bot IPs
	if ( !empty($bot_ip) )
	{
		foreach ( $bot_ip as $bot_id => $ip)
		{
			if ( $ip && strpos(trim($user_ip), $ip) === 0)
			{
				$bot_ip_match = $bot_id;
				break;
			}
		}
	}

	//See if the user_agent matches one in our list of known search bot agents, if the IP was matched
	if ( !empty($bot_agent) && $bot_ip_match != -1 )
	{
		foreach ( $bot_agent as $bot_id => $agent )
		{
			if ($agent && strpos(strtolower($user_agent), strtolower($agent)) !== false)
			{
				$bot_agent_match = $bot_id;
				break;
			}
		}
	}

	//Compare the detected IP address and user_agent, if they are the same are match is found.
	//Else, it is probably someone spoofing so return no match.
	if ( ($bot_ip_match != -1 && $bot_agent_match != -1) && ($bot_name[$bot_ip_match] == $bot_name[$bot_agent_match]) )
	{
		return $bot_agent_match;
	}
	else
	{
		return -1;
	}
}

function add_crumb($url, $title)
{
	global $bread_crumbs;
	
	$crumb = array('url' => $url, 'title' => $title);
	$bread_crumbs[] = $crumb;
}

function display_crumbs($page_location)
{
	global $template, $bread_crumbs;
	
	if ($page_location == 'header' || $page_location == 'footer')
	{
		$breadcrumb_css = $page_location;
	}
	else
	{
		$breadcrumb_css = 'header';	
	}
	
	
}




function make_url_friendly($url)
{

	$url = strtolower($url);

	// Fix for most recent topics block
	// or else a b is shown in every url
	$find = array('<b>',
		'</b>');
	$url = str_replace ($find, '', $url);

	// we use this instead of urlencode since we dont want everything encoded.
	// These only pertain to other character sets and are needed to help those
	// keep the original enteded meaning for that language.
	// We are limited in this though since not all characters are able to be converted.
	$find = array('æ','Š','Œ','Ž','š','œ','ž','Ÿ','¡','¥','§','¨','ª','µ','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ');

	$repl = array('%00','%8a','%8c','%8e','%9a','%9c','%9e','%9f','%a1','%a5','%a7','%a8','%aa','%b5','%bf','%c0','%c1','%c2','%c3','%c4','%c5','%c6','%c7','%c8','%c9','%ca','%cb','%cc','%cd','%ce','%cf','%d0','%d1','%d2','%d3','%d4','%d5','%d6','%d8','%d9','%da','%db','%dc','%dd','%de','%df','%e0','%e1','%e2','%e3','%e4','%e5','%e6','%e7','%e8','%e9','%ea','%eb','%ec','%ed','%ee','%ef','%f0','%f1','%f2','%f3','%f4','%f5','%f6','%f8','%f9','%fa','%fb','%fc','%fd','%fe','%ff');

	$url = str_replace ($find, $repl, $url);

	$find = array(' ',
		'&quot;',
		'&',
		'\r\n',
		'\n',
		'/',
		'\\',
		'+',
		'<',
		'>');
	$url = str_replace ($find, '-', $url);

	$find = array('/[^a-z0-9\-<>]/',
		'/[\-]+/',
		'/<[^>]*>/');

	$repl = array('',
		'-',
		'');

	$url =  preg_replace ($find, $repl, $url);

	$url = str_replace ('--', '-', $url);

	return $url;
}


function replace_for_mod_rewrite(&$s) 
{ 

   if (empty($_SERVER['HTTP_HOST'])) 
   { 
      $server = getenv('HTTP_HOST'); 
   } 
   else 
   { 
      $server = $_SERVER['HTTP_HOST']; 
   } 

   if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') 
   { 
      $proto = 'https://'; 
   } 
   else 
   { 
      $proto = 'http://'; 
   } 


   $base_url = $proto . $server . "/";


   $urlin = array( 

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)="|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|', 

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)="|',

      '|"' . $base_url . '([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . '(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"' . $base_url . 'error.php"|',

      '|"' . $base_url . 'help.php"|',

      '|"' . $base_url . 'groupcp.php"|',

      '|"' . $base_url . 'index.php"|',

      '|"' . $base_url . 'login.php"|',

      '|"' . $base_url . 'register.php"|',

      '|"' . $base_url . 'profile.php"|',

      '|"' . $base_url . 'search.php"|',

      '|"' . $base_url . 'policy.php"|',

//----------------------------------------

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)="|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)&(?:amp;)([[:alnum:]%+\.\_\'\"\#]+)="|',

      '|"([[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"(./[[:alnum:]%+\.\_\'\"\#]+).php\?([[:alnum:]%+\.\_\'\"\#]+)=([[:alnum:]%+\.\_\'\"\#]+)"|',

      '|"error.php"|', 

      '|"help.php"|',

      '|"groupcp.php"|',

      '|"index.php"|',

      '|"login.php"|',

      '|"register.php"|',

      '|"profile.php"|',

      '|"search.php"|',
 
      '|"policy.php"|', 

 
   ); 

   $urlout = array( 

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11-\\12=\\13-\\14=\\15"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11-\\12=\\13"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8="',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5"',

      '"' . $base_url . '\\1-\\2=\\3-\\4="',

      '"' . $base_url . '\\1-\\2=\\3"',

      '"' . $base_url . '\\1-\\2=\\3"',

      '"' . $base_url . 'error"',

      '"' . $base_url . 'help"', 

      '"' . $base_url . 'groupcp"',

      '"' . $base_url . 'index"',

      '"' . $base_url . 'login"',

      '"' . $base_url . 'register"',

      '"' . $base_url . 'profile"',

      '"' . $base_url . 'search"',

      '"' . $base_url . 'policy"',

//------------------------------------


      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11-\\12=\\13-\\14=\\15"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11-\\12=\\13"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9-\\10=\\11"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8=\\9"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7-\\8="',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5-\\6=\\7"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5"',

      '"' . $base_url . '\\1-\\2=\\3-\\4=\\5"',

      '"' . $base_url . '\\1-\\2=\\3-\\4="',

      '"' . $base_url . '\\1-\\2=\\3"',

      '"' . $base_url . '\\1-\\2=\\3"',

      '"' . $base_url . 'error"',

      '"' . $base_url . 'help"',

      '"' . $base_url . 'groupcp"',

      '"' . $base_url . 'index"',

      '"' . $base_url . 'login"',

      '"' . $base_url . 'register"',

      '"' . $base_url . 'profile"',

      '"' . $base_url . 'search"', 
 
      '"' . $base_url . 'policy"',

   );
 
   $s = preg_replace($urlin, $urlout, $s); 
   return $s; 
} 

?>